package com.ziq.zcamp.dialog.share

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Bitmap
import android.net.Uri
import android.util.AttributeSet
import android.util.TypedValue
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.view.isVisible
import com.blankj.utilcode.util.ScreenUtils
import com.facebook.common.util.UriUtil
import com.facebook.imagepipeline.request.ImageRequest
import com.ziq.base.extension.dp
import com.ziq.zcamp.R
import com.ziq.zcamp.api.request.common.MiniACodeParam
import com.ziq.zcamp.api.service.ApiUrlHelper
import com.ziq.zcamp.bean.activities.ActivitiesInfo
import com.ziq.zcamp.bean.coupon.CouponInfo
import com.ziq.zcamp.bean.life.CampLifeInfo
import com.ziq.zcamp.bean.place.PlaceDetail
import com.ziq.zcamp.bean.post.PostingDetail
import com.ziq.zcamp.bean.product.PlaceProduct
import com.ziq.zcamp.constant.H5Url
import com.ziq.zcamp.constant.MerchantCouponType
import com.ziq.zcamp.databinding.LayoutSharePicBinding
import com.ziq.zcamp.manager.GlobalContextManager
import com.ziq.zcamp.manager.UserManager
import com.ziq.zcamp.merchant.coupon.CouponAdapterHelper
import com.ziq.zcamp.util.ImageUtil
import com.ziq.zcamp.util.TimeUtil
import com.ziq.zcamp.util.blurry.Blurry
import java.net.URLEncoder
import java.text.DecimalFormat


class SharePicLayout @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr) {

    var binding : LayoutSharePicBinding = LayoutSharePicBinding.inflate(LayoutInflater.from(context), this, true)

    private val uidSuffix by lazy{
        val id = UserManager.instance.userInfo.value?.id.toString()
        if (id.isEmpty()){
            ""
        }else{
            "&shareuid=${id}"
        }
    }

    fun setPostingData(data: PostingDetail){
        val width = ScreenUtils.getScreenWidth() - GlobalContextManager.getResources().getDimensionPixelSize(
            R.dimen.dimens_dip_28) * 2
        val height = width / 375.0 * 667.0
        val lp = layoutParams as ViewGroup.LayoutParams
        lp.width = width
        lp.height = height.toInt()
        layoutParams = lp
        binding.containerPosting.visibility = View.VISIBLE

        data.user?.let {
            binding.name.text = it.nick_name
            binding.avator.setImageURI(it.header_url)
        }
        data.post?.let {
            binding.imagePosting.setImageURI(it.images?.get(0)?.url?:"")
            if(it.title?.isNotEmpty() == true){
                binding.title.visibility = View.VISIBLE
                binding.title.text = it.title
            }
            if(it.content?.isNotEmpty() == true){
                binding.content.visibility = View.VISIBLE
                binding.content.text = it.content
            }
            if(it.p_type == 2){
                binding.ivVideoBtn.visibility = View.VISIBLE
                binding.tvPostTypeDescription.text = "发布了一个视频"
            } else if(it.p_type == 3){
                binding.tvPostTypeDescription.text = "发布了一篇文章"
            }
        }
        var url = ""
        var miniPagePath = ""
        var miniPageScene = ""
        when(data?.post?.p_type){
            1, 3->{
                url = ApiUrlHelper.instance.getUrl("${H5Url.POSTING_DETAIL.url}?id=${data?.post?.post_id}&creatorId=${data?.user?.uid}${uidSuffix}")
                miniPagePath = "subpages/community/post-detail/index"
                miniPageScene = "id=${data!!.post?.post_id}&creatorId=${data!!.user?.uid}${uidSuffix}&share_cv="
            }
            2->{
                url = ApiUrlHelper.instance.getUrl("${H5Url.POST_VIDEO_DETAIL.url}?id=${data?.post?.post_id}&creatorId=${data?.user?.uid}${uidSuffix}")
                miniPagePath = "subpages/community/video-detail/index"
                miniPageScene = "id=${data!!.post?.post_id}&creatorId=${data!!.user?.uid}${uidSuffix}&share_cv="
            }
            else -> {
            }
        }
        showMiniCode(
            miniPagePath,
            miniPageScene,
            url
        )
    }

    fun setPlaceData(data: PlaceDetail){
        val width = ScreenUtils.getScreenWidth() - GlobalContextManager.getResources().getDimensionPixelSize(R.dimen.dimens_dip_28) * 2
        val height = width / 375.0 * 700.0
        val lp = layoutParams as ViewGroup.LayoutParams
        lp.width = width
        lp.height = height.toInt()
        layoutParams = lp
        binding.containerPlace.visibility = View.VISIBLE
        data.camp?.let {
            binding.placeName.text = it.camp_name
            val isFieldCamp = it.camp_type == 2
            if(isFieldCamp){
                binding.tvLocation.text = "打开小程序解锁地址"
            } else {
                binding.tvLocation.text = it.location_addr
            }


            if(it.images != null){
                val length = it.images!!.size
                if(length > 3){
                    binding.llPlaceFourImage.visibility = View.VISIBLE
                    binding.imagePlaceOne.setImageURI(it.images?.get(0)?.source?:(it.images?.get(0)?.url?:""))
                    binding.imagePlaceTwo.setImageURI(it.images?.get(1)?.source?:(it.images?.get(1)?.url?:""))
                    binding.imagePlaceThree.setImageURI(it.images?.get(2)?.source?:(it.images?.get(2)?.url?:""))
                    binding.imagePlaceFour.setImageURI(it.images?.get(3)?.source?:(it.images?.get(3)?.url?:""))
                }else {
                    binding.imagePlaceSingle.visibility = View.VISIBLE
                    binding.imagePlaceSingle.setImageURI(it.images?.get(0)?.source?:(it.images?.get(0)?.url?:""))
                }
            }

        }

        showMiniCode(
            "subpages/camp/camp-detail/index",
            "id=${data!!.camp?.id}${uidSuffix}&share_cv=",
            ApiUrlHelper.instance.getUrl("${H5Url.PLACE_DETAIL.url}?id=${data.camp?.id?:""}${uidSuffix}")
        )
    }

    @SuppressLint("SetTextI18n")
    fun setActivityData(data: ActivitiesInfo){
        val width = ScreenUtils.getScreenWidth() - GlobalContextManager.getResources().getDimensionPixelSize(R.dimen.dimens_dip_28) * 2
        val height = ViewGroup.LayoutParams.WRAP_CONTENT
        val lp = layoutParams as ViewGroup.LayoutParams
        lp.width = width
        lp.height = height
        layoutParams = lp
        binding.containerActivity.visibility = View.VISIBLE
        binding.ivIconCamp.visibility = View.GONE
        data.images?.let {
            if (it.isNotEmpty()){
                ImageUtil.updateImageFromNetwork(binding.ivActivitiesPoster,it[0].url?:"", ImageRequest.CacheChoice.DEFAULT)

                ImageUtil.getBitmap(0, it[0].url,ImageUtil.imageMaxSize, ImageUtil.imageMaxSize, ImageUtil.imageMaxSize) { _, bitmap ->
                    if (ImageUtil.isBitmapAvailable(bitmap)) {
                        Blurry.with(context)
                            .radius(10)
                            .sampling(8)
                            .color(resources.getColor(R.color.black_translucent_60))
                            .from(bitmap)
                            .into(binding.vMaskActivityInfo)
                    }
                }
            }
        }
        binding.tvActivitiesName.text = data.title
        if (data.start_show_time != null && data.end_show_time!= null){
            if (data.start_show_time.equals(data.end_show_time)){
                binding.tvActivitiesTime.text = "${data.start_show_time}"
            }else{
                binding.tvActivitiesTime.text = "${data.start_show_time}-${data.end_show_time}"
            }
        }else if (data.start_show_time!=null){
            binding.tvActivitiesTime.text = "${data.start_show_time}"
        }else{
            binding.tvActivitiesTime.text = "--:--"
        }
        binding.tvActivitiesPlace.text = data.location_addr
        if (!data.price_range.isNullOrEmpty() && data.free_type != 1){
            val min = data.price_range?.minOrNull()
            val string = DecimalFormat("0.00").format((min?:0) / 100f)
            binding.tvActivitiesPrice.text =  "￥$string 起"
        }else if ( data.free_type == 1){
            binding.tvActivitiesPrice.text =  "免费"
        }else{
            binding.tvActivitiesPrice.text =  ""
        }
        data.related_camp.let {
            if (it!=null && !it.isInfoEmpty()){
                binding.groupCamp.visibility = View.VISIBLE
                binding.tvActivitiesCamp.text = it.name
            }else{
                binding.groupCamp.visibility = View.GONE
            }
        }
        data.organizer.let {
            if (it!=null){
                binding.llActivitiesSponsor.visibility = View.VISIBLE
                ImageUtil.updateImageFromNetwork(binding.ivActivitiesHeadPortrait,it.portrait, ImageRequest.CacheChoice.DEFAULT)
                binding.tvActivitiesUserName.text = it.nick
            }else{
                binding.llActivitiesSponsor.visibility = View.GONE
            }
        }

        data.vr.let {
            if (it != null && it.exist_vr == true){
                binding.llActivitiesVr.visibility = View.VISIBLE
            }else{
                binding.llActivitiesVr.visibility = View.GONE
            }
        }

        showMiniCode(
            "subpages/community/activity-detail/index",
            "id=${data?.id}&from=1${uidSuffix}&share_cv=",
            ApiUrlHelper.instance.getUrl("${H5Url.ACTIVITY_DETAILS.url}/?id=${data.id?:""}&from=2${uidSuffix}")
        )

        binding.llQrCodeBg.visibility = View.GONE
        val qrlp = binding.llQrCode.layoutParams  as ConstraintLayout.LayoutParams
        qrlp.bottomMargin = 20.dp
        binding.llQrCode.layoutParams = qrlp
    }

    @SuppressLint("SetTextI18n")
    fun setCampLifeData(data: CampLifeInfo){
        val width = ScreenUtils.getScreenWidth() - GlobalContextManager.getResources().getDimensionPixelSize(R.dimen.dimens_dip_28) * 2
        val height = width / 375.0 * 600.0
        val lp = layoutParams as ViewGroup.LayoutParams
        lp.width = width
        lp.height = height.toInt()
        layoutParams = lp

        binding.containerCampLife.visibility = View.VISIBLE
        data.user_image.let {
            if (it == null){
                binding.ivUserImage.setImageResource(R.drawable.icon_default_avatar)
            }else{
                ImageUtil.updateImageFromNetwork(binding.ivUserImage, data.user_image, ImageRequest.CacheChoice.DEFAULT)
            }
        }
        data.user_name.let {
            if (it == null){
                binding.tvUserTitle.text = "${data.user_name}"

            }else{
                binding.tvUserTitle.text = "${data.user_name}的露营人生"
            }
        }
        binding.tvCampTime.text = data.time

        val list = mutableListOf(data.camp_num?:0,data.place_num?:0, data.city_num?:0)
        val max = list.maxOrNull()
        val len = max.toString().length
        val difference = if (len > 3) (len -3 ) * 8 else 0
        binding.tvNumOfCamp.setTextSize(TypedValue.COMPLEX_UNIT_DIP,32.0F - difference)
        binding.tvNumOfPlace.setTextSize(TypedValue.COMPLEX_UNIT_DIP,32.0F - difference)
        binding.tvNumOfCity.setTextSize(TypedValue.COMPLEX_UNIT_DIP,32.0F - difference)

        binding.tvNumOfCamp.text = data.camp_num.toString()
        binding.tvNumOfPlace.text = data.place_num.toString()
        binding.tvNumOfCity.text = data.city_num.toString()

        val uri: Uri = Uri.Builder()
            .scheme(UriUtil.LOCAL_FILE_SCHEME)
            .path(data.map_image)
            .build()
        binding.ivMapImage.setImageURI(uri)

        ImageUtil.updateImageFromNetwork(binding.ivAppletCode, data.mini_image, ImageRequest.CacheChoice.DEFAULT)
        binding.ivIconCamp.visibility = View.GONE
    }

    @SuppressLint("SetTextI18n")
    fun setCouponData(data: CouponInfo) {
        val width = ScreenUtils.getScreenWidth() - GlobalContextManager.getResources().getDimensionPixelSize(R.dimen.dimens_dip_27_5) * 2
        val height = width / 375.0 * 446.0
        val lp = layoutParams as ViewGroup.LayoutParams
        lp.width = width
        lp.height = height.toInt()
        layoutParams = lp

        binding.containerCampCoupon.visibility = View.VISIBLE

        binding.tvDiscountRange.text = when(data.applicate){
            1->{"指定商品"}
            else->{"全场通用"}
        }
        when(data.coupon_type){
            MerchantCouponType.Discount.value ->{
                binding.tvDiscountSymbol.isVisible = false
                binding.tvDiscountDiscount.isVisible = true

                binding.tvDiscountNumerical.text =
                    CouponAdapterHelper.obtainMoneyRate(data.discounts_way?.rate_off_way?.rate)

                binding.tvDiscountName.text = "满￥${CouponAdapterHelper.obtainMoneyText(data.discounts_way?.rate_off_way?.full_money)}可用"
            }
            MerchantCouponType.Reduction.value ->{
                binding.tvDiscountSymbol.isVisible = true
                binding.tvDiscountDiscount.isVisible = false

                binding.tvDiscountNumerical.text =
                    CouponAdapterHelper.obtainMoneyText(data.discounts_way?.money_off_way?.discount_money)

                binding.tvDiscountName.text = "满￥${CouponAdapterHelper.obtainMoneyText(data.discounts_way?.money_off_way?.full_money)}可用"
            }
        }
        binding.tvDiscountSurplus.text = "每人限领1张"
        val timeStringBuilder = StringBuilder()
        timeStringBuilder.append("有效期始：${TimeUtil.yyyy_MM_dd_time_SPOT_FORMATTER_CN.format((data.available_begin_time?:0)*1000L)}\n")
        timeStringBuilder.append("有效期至：${TimeUtil.yyyy_MM_dd_time_SPOT_FORMATTER_CN.format((data.available_end_time?:0)*1000L)}")
        binding.tvDiscountTime.text = timeStringBuilder.toString()
        binding.tvCampName.text = data.camp_name

        val uidSuffix by lazy{
            val id = UserManager.instance.userInfo.value?.id.toString()
            if (id.isEmpty()){
                ""
            }else{
                "&shareuid=${id}"
            }
        }
        val target = "${H5Url.RECEIVE_COUPON.url}?source=wx_scan_code&camp_id=${data.camp_id}&stock_id=${data.stock_id}${uidSuffix}"
        val url = ApiUrlHelper.instance.getUrl("${H5Url.COUPON_SHARE.url}${URLEncoder.encode(target)}")

        ShareUtil.getQRCode(url, onSuccess = {
            binding.ivQrCode.post {
                binding.ivQrCode.setImageBitmap(it)
            }
        })

        binding.ivIconCamp.visibility = View.GONE
    }

    @SuppressLint("SetTextI18n")
    fun setPlaceProductData(data: PlaceProduct) {
        val width = ScreenUtils.getScreenWidth() - GlobalContextManager.getResources().getDimensionPixelSize(R.dimen.dimens_dip_27_5) * 2
        val height = width / 375.0 * 667.0
        val lp = layoutParams as ViewGroup.LayoutParams
        lp.width = width
        lp.height = height.toInt()
        layoutParams = lp
        binding.containerPlaceProduct.visibility = View.VISIBLE


        if(data.goods_url_list?.isNotEmpty() == true){
            ImageUtil.updateImageFromNetwork(binding.imagePlaceProductSingle, data.goods_url_list?.get(0)?.url?:"", ImageRequest.CacheChoice.DEFAULT)
        }

        binding.placeProductName.text = data.name

        if((data?.price_range?.size?:0) > 0){
            val li = data?.price_range?.sortedBy { it }
            if((li?.first()?:0) == (li?.last()?:0)){
                binding.placeProductPrice.text = "${DecimalFormat("0.##").format((li?.first()?:0) / 100f)}"
            }else {
                binding.placeProductPrice.text = "${DecimalFormat("0.##").format((li?.first()?:0) / 100f)}-${DecimalFormat("0.00").format((li?.last()?:0) / 100f)}"
            }
        }else {
            binding.placeProductPrice.text = "${DecimalFormat("0.##").format((data?.price?:0) / 100f)}"
        }

        showMiniCode(
            "subpages/camp/commodity-detail/index",
            "id=${data.commodity_id}${uidSuffix}&share_cv=",
            ApiUrlHelper.instance.getUrl("${H5Url.PLACE_PRODUCT_DETAIL.url}?id=${data.commodity_id?:""}${uidSuffix}")
        )
    }


    fun showMiniCode(miniPagePath:String, miniPageScene:String, qrUrl:String){
        binding.llQrCode.visibility = View.VISIBLE
        binding.llQrCodeBg.visibility = View.VISIBLE
        ShareUtil.getSanCode(MiniACodeParam().apply {
            is_hyaline = true
            page = miniPagePath
            scene = miniPageScene
            width = 280.toString()
        }, qrUrl,  onSuccess = { minCodeUrl:String, bitmap: Bitmap->
            binding.qrCode.post {
                binding.qrCode.setImageBitmap(bitmap)
            }
            if(minCodeUrl.isNotEmpty()){
                binding.qrCodeBottomTxt.text = "识别小程序码 阅读完整内容"
            } else {
                binding.qrCodeBottomTxt.text = "识别二维码 阅读完整内容"
            }
        })
    }
}